from flask import Blueprint, request, jsonify
from model import db, User, Role, UserToRole
from sqlalchemy import select

ucenter_router = Blueprint("ucenter", __name__, url_prefix="/ucenter")

@ucenter_router.route("/add/user", methods=("POST",))
def add_user():
    """
        批量添加用户
    """
    data: dict = dict(request.get_json(silent=True))
    user_list = [User(name=data["name"]+str(i)) for i in range(1,3)]
    with db.session.begin():
        db.session.add_all(user_list)
    db.session.commit()
    return {"msg": "ok"}

@ucenter_router.route("/add/role", methods=("POST",))
def add_role():
    """
        批量添加角色
    """
    data: dict = dict(request.get_json(silent=True))
    role_list = [Role(name=data["name"]+ str(i))for i in range(3)]
    with db.session.begin():
        db.session.add_all(role_list)
    db.session.commit()
    return {"msg": "ok"}



@ucenter_router.route("/user/add/role", methods=("POST",))
def user_add_role():
    """
        用户(user)添加角色(role)
    """

    data: dict = request.get_json(silent=True)
    user = db.session.get(User, data["user_id"])
    
    roles = db.session.execute(select(Role).where(Role.id.in_(data["role_id_list"]))).scalars().all()
    user.roles = roles
    db.session.add(user)
    # db.session.append(role) # 插入
    # db.session.remove(role) # 移除
    db.session.commit()
    return {"msg": "ok"}

@ucenter_router.route("/user_to_role/list")
def user_to_role():
    """
        查询中间表
    """
    ur_list = db.session.execute(select(UserToRole).limit(5)).scalars()
    resp = []
    for ur in ur_list:
        resp.append({
            "id": ur.id,
            "user_id": ur.user_id,
            "role_id": ur.role_id,
        })
    return jsonify(resp)
